<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { fetchDelUserById, fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusRecord } from '@/constants/business';
import { useAuth } from '@/hooks/business/auth';
import UserOperateModal from '@/views/manage/user/modules/user-operate-modal.vue';

const { hasAuth } = useAuth();
const wrapperRef = ref<HTMLElement | null>(null);
const appStore = useAppStore();
const { data, columns, columnChecks, getData, loading, mobilePagination } = useTable({
  apiFn: fetchGetUserList,
  apiParams: {
    current: 1,
    size: 10,
    account: '',
    realName: '',
    phone: '',
    status: null,
    nickName: ''
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48,
      fixed: 'left'
    },
    {
      key: 'account',
      title: $t('page.manage.user.account'),
      width: 120,
      align: 'center'
    },
    {
      key: 'realName',
      title: $t('page.manage.user.realName'),
      width: 120,
      align: 'center'
    },
    {
      key: 'nickName',
      title: $t('page.manage.user.nickName'),
      width: 120,
      align: 'center'
    },
    {
      key: 'status',
      title: $t('page.manage.user.status'),
      width: 80,
      align: 'center',
      render: row => {
        if (row.status === null) {
          return null;
        }
        const label = $t(enableStatusRecord[row.status]);
        return <NTag type={row.status === '1' ? 'success' : 'warning'}>{label}</NTag>;
      }
    },
    {
      key: 'phone',
      title: $t('page.manage.user.phone'),
      width: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 220,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {hasAuth('sys:user:edit') && (
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {$t('common.edit')}
            </NButton>
          )}
          {hasAuth('sys:user:del') && (
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {$t('common.delete')}
                  </NButton>
                )
              }}
            </NPopconfirm>
          )}
        </div>
      )
    }
  ]
});
const { operateType, editingData, handleEdit, handleAdd, onDeleted, checkedRowKeys, onBatchDeleted, drawerVisible } =
  useTableOperate(data, getData);

async function edit(id: number) {
  await handleEdit(id);
}
function handleBatchDelete() {
  onBatchDeleted();
}
async function handleDelete(id: number) {
  const { error, data: result } = await fetchDelUserById(id);
  if (!error && result) {
    window.$message?.success($t('common.deleteSuccess'));
    await onDeleted();
  }
}
</script>

<template>
  <div ref="wrapperRef" class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.manage.user.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          add-auth="sys:user:add"
          delete-auth="sys:user:del"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :data="data"
        :columns="columns"
        :pagination="mobilePagination"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        class="sm:h-full"
      />
      <UserOperateModal
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
